//
//  VinHTTPCache.m
//  SWCommonFrame
//
//  Created by shaowei on 13-6-17.
//  Copyright (c) 2013年 shaowei. All rights reserved.
//

#import "SWHTTPCache.h"
#import "CaculateMD5.h"

static SWHTTPCache *sInstance;

@implementation SWHTTPCache

- (id)init
{
    self = [super init];
    if (self) {
        
        //缓存路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
        NSString *cacheFolderName = [@"SW" stringByAppendingString:appName];
        self.diskCachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:cacheFolderName];
        
        //创建缓存文件夹
        if (![[NSFileManager defaultManager] fileExistsAtPath:_diskCachePath])
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:_diskCachePath
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
        
        //缓存保存的线程队列
        _cacheStoreQueue = [[NSOperationQueue alloc] init];
        _cacheStoreQueue.maxConcurrentOperationCount = 1;
    }
    return self;
}

- (void)dealloc
{
    [_diskCachePath release];
    [_cacheStoreQueue release];
    [super dealloc];
}

#pragma mark - Function - Public

+ (SWHTTPCache *)sharedDataCache{
    if (!sInstance) {
        sInstance = [[SWHTTPCache alloc] init];
    }
    return sInstance;
}

- (void)storeData:(NSData *)data forKey:(NSString *)key{
    if (data && key) {
        //数据不能为空
        NSArray *keyWithData = [NSArray arrayWithObjects:key, data, nil];
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                                selector:@selector(storeKeyWithDataToDisk:)
                                                                                  object:keyWithData];
        [_cacheStoreQueue addOperation:operation];
    }else{
        NSAssert2(0, @"数据缓存参数有空值：\nkey:%@.\ndata:%@",key, data);
    }
    
}

- (NSData *)queryDiskCacheForKey:(NSString *)key{
    NSString *path = [self cachePathForKey:key];
    NSData *subData = [NSData dataWithContentsOfFile:path];
    return subData;
}

#pragma mark Function - Private

//存储NSData到硬盘的实际操作
- (void)storeKeyWithDataToDisk:(NSArray *)keyAndData
{
    // Can't use defaultManager another thread
    //    NSFileManager *fileManager = [[NSFileManager alloc] init];
#warning  NSFileManager 可能为空
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *key = [keyAndData objectAtIndex:0];
    NSData *data = [keyAndData count] > 1 ? [keyAndData objectAtIndex:1] : nil;
    
    if (data)
    {
        [fileManager createFileAtPath:[self cachePathForKey:key] contents:data attributes:nil];
    }
}

//文件名编码
+ (NSString *)stringEncode:(NSString *)fileName{
    return [CaculateMD5 calculateMD5WithString:fileName];
}

//获取文件默认的存储路径，同时处理了文件名的编码问题
- (NSString *)cachePathForKey:(NSString *)key{
    NSString *encodeKey = [SWHTTPCache stringEncode:key];
    NSString *path = [self.diskCachePath stringByAppendingPathComponent:encodeKey];
    return path;
}



@end
